<%@page import="java.awt.print.Printable"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>_${customer.customerName}_入库点收</title>
<style type="text/css">
	.chosen-container {
		width: 100%!important;
	}
</style>
<script type='text/javascript'
      src='http://wms.ttyuncang.com/WebSpeech.js'></script>
<script type='text/javascript'
      src='${ctx}/static/js/map.js'></script>
<script type="text/javascript" src="${ctx}/static/v2/js/modal.js"></script>
<script type="text/javascript">
	var skuLockValue="";
	var curSku="";
	var  skuMap=new Map();
	$(function() {
		//如果点收已经完成，隐藏操作按钮
		$("#txt_num").val("1");
		$("#txt_lpn").val("");
		$("#txt_lpn").focus();
		//锁定数量
		$("#lock_num").iCheck({checkboxClass: 'icheckbox_minimal'});
		$("#lock_num").parent().attr('aria-checked','true');
		$('#lock_num').on('ifChecked', function (event) {
			$("#txt_num").attr("readOnly", true);
        });
        $('#lock_num').on('ifUnchecked', function (event) {
        	$("#txt_num").removeAttr("readOnly");
        	$("#txt_num").val('');
        });
		//锁定sku
		$("#lock_sku").iCheck({checkboxClass: 'icheckbox_minimal'});
		$('#lock_sku').on('ifChecked', function (event) {
			if($("#txt_sku_1").val().trim().length==0){
				$("#msg_1").css("color", "red");
				$("#msg_1").html("SKU为空，不能锁定，请先输入SKU");
			}else{
				skuLockValue=$("#txt_sku_1").val().trim();
			}
			
        });
        $('#lock_sku').on('ifUnchecked', function (event) {
        	skuLockValue="";
        });
	});

	WebSpeech.ready(function() {
		WebSpeech.speak('听到声音了吗？');
	});
	// 清空弹框的值并隐藏显示
	function clearBatch() {
		$('#txt_batchCode').val('');
		$('#txt_productDate').val('');
		$('#txt_expireDate').val('');
	  	$('.txt_batchCode').css('display','none');
	  	$('.txt_expireDate').css('display','none');
	}

	// SKU的enter事件
	var batchTime = 0;
	function keydown_key() {
		var lock_num = $("#lock_num").parent().attr('aria-checked');
		keydown_1();
	}

	// 验证是否受批次控制
	function keydown_1() {
		var lock_num = $("#lock_num").parent().attr('aria-checked');
		var customerCode="${task.customerCode}";
	  	var billCode="${task.billCode}"; 
	  	var sku = $("#txt_sku_1").val().trim();
		$.ajax({
			type:'post',
			url:'${ctx}/v2_instorageCount/findSku',
			data:{
				billCode:billCode,
				customerCode:customerCode,
				sku:sku
			},
			dataType:'json',
			async: false,
			cache: false,
			success:function(data) {
				if(data.status == "success"){
					if(data.isShelfLifeMgmt != 0 || data.isBatchMgmt != 0){
						var batchList, batchCode_modal, productDate_modal, expireDate_modal, model_data;
						batch(data.isShelfLifeMgmt, data.isBatchMgmt, data.batchList ,function(batchList){
							batchTime = 1;
							batchCode_modal = batchList[0].batch_input == undefined ? '' : batchList[0].batch_input;
							productDate_modal = batchList[1].batch_start == undefined ? '' : batchList[1].batch_start;
							expireDate_modal = batchList[2].batch_end == undefined ? '' : batchList[2].batch_end;
							if (data.isBatchMgmt != 0) {
								$("#txt_batchCode").val(batchCode_modal);
								$('.txt_batchCode').css('display','inline-block');
							}
							if (data.isShelfLifeMgmt != 0) {
								$("#txt_productDate").val(productDate_modal);
								$("#txt_expireDate").val(expireDate_modal);
								$('.txt_expireDate').css('display','inline-block');
							}

					  	  	if(lock_num == 'true'){
					  		  	numAdd();
					  	  	}else{
					  		  	$("#txt_num").focus();
					  	  	}
						});
					}else{
						batchCode = '';
						productDate = '';
						expireDate = '';
						if(lock_num == 'true'){
				  		  	numAdd();
				  	  	}else{
				  		  	$("#txt_num").focus();
				  	  	}
					}
					return 1;
			    }else if(data.status == "skuNotExist"){
			       alert(data.content);
			       $("#txt_sku_1").val('');
			       $("#txt_sku_1").focus();
			       if(!(lock_num == 'true')){
			       		$('#txt_num').val('');
			       }
			    }else {
			      alert("网络繁忙，请稍后重试...");
			    }
			},
			error:function() {
				alert("网络繁忙，请稍后重试...");
			}
	   	});
	}

	// 验证lpn是否可用
	function lpnChange(event){
		var lpnNum=$("#txt_lpn").val().trim();
		var warehouseCode="${task.inwarehouseCode}";
		var ev = document.all ? window.event : event;
		if(ev.keyCode == 13){
			 $.ajax({
				   type : 'post',
					url : '${ctx}/v2_instorageBillNew/lpnCheck',
					async:false,
					data : {
						lpnNum:lpnNum,
						warehouseCode:warehouseCode
					},
					dataType : 'json',
					success : function(data) {
						var status=data.status;
						var content = data.content;
						if( status=='success'){
							$("#txt_sku_1").focus();
							// $("#txt_sku_1").select();
						}else{
							alert(content);
							$("#txt_lpn").val("");
							$("#txt_lpn").focus();
						}
					},
					error : function() {
						jAlert("网络繁忙，请稍后重试...","温馨提示");
					}
				}); 
		}
	}

	// SKU变化则清空弹框的值
	function sku1Change() {
		clearBatch();
	}

	// 破损件的变化控制
	function errorChange() {
		var lock_num = $("#lock_num").parent().attr('aria-checked');
		if (!(lock_num == 'true')) {
			$("#txt_num").val('');
		}
		$("#txt_sku_1").val('');
	}

	// 数量变化时判断是否验证弹框
	function numChange() {
		if (batchTime == 0) {
			keydown_1();
		}
	}

	// 添加点收数量等操作
	function numAdd() {
		var errorflag = $("#error_flag").val();
		var sku = $("#txt_sku_1").val().trim();
		var batchCode = $("#txt_batchCode").val().trim();
		var productDate = $("#txt_productDate").val().trim();
		var expireDate = $("#txt_expireDate").val().trim();
		var num = $("#txt_num").val().trim();
		if (errorflag == 0) {
			$("#msg_1").css("color", "red");
			$("#msg_1").html("请选择报损的状态");
			$("#error_flag").select();
			$("#error_flag").focus();
			return false;
		}

		if (sku.length == 0) {
			$("#msg_1").css("color", "red");
			$("#msg_1").html("请输入sku!");
			$("#txt_sku_1").select();
			$("#txt_sku_1").focus();
			return false;
		}

		if (num.length == 0) {
			$("#msg_1").css("color", "red");
			$("#msg_1").html("请输入数量!");
			$("#txt_num").select();
			$("#txt_num").focus();
			return false;
		}

		if (isNaN(num)) {
			$("#msg_1").css("color", "red");
			$("#msg_1").html("请输入正确的数字!");
			$("#txt_num").select();
			$("#txt_num").focus();
			return false;
		}

		if (num == 0) {
			$("#msg_1").css("color", "red");
			$("#msg_1").html("点收数量不能为0!");
			$("#txt_num").select();
			$("#txt_num").focus();
			return false;
		}
		
		var i = 0;
		var flag=0;
		var firstTr;
		var secondTr;
		$("#boxItem").find("tr").each(function(j) {
			var tdArr = $(this).find("td");
			var val1 = tdArr.eq(1).text().trim();
			var val2 = tdArr.eq(2).text().trim();
			var val3 = tdArr.eq(3).text().trim();
			var val4 = tdArr.eq(4).text().trim();
			if (val1 == sku && (batchCode=='' || (val2 == batchCode)) && (productDate=='' || (val3 == productDate)) && (expireDate=='' || (val4 == expireDate))) {
				secondTr=tdArr;
				flag=j;
				//点收数量+扫描数量+已收货数量要小于预约数量
				if ((parseInt(num)+parseInt(tdArr.eq(7).text())+parseInt(tdArr.eq(8).text())) > parseInt(tdArr.eq(6).text())) {
					i = -1;
				} else if((parseInt(num)+parseInt(tdArr.eq(7).text())+parseInt(tdArr.eq(8).text())) == parseInt(tdArr.eq(6).text())){
					i = 2;
					var scannum = parseInt(tdArr.eq(7).text()) + parseInt(num);
					//tdArr.eq(4).style.backgroundColor = "green";
					tdArr.eq(7).html(scannum);
				} else{
					i = 1;
					var scannum = parseInt(tdArr.eq(7).text()) + parseInt(num);
					tdArr.eq(7).html(scannum);
				}
			}
		});

		$("#boxItem tr:eq("+flag+")").insertBefore( $("#boxItem tr:eq(0)"));
		if (i == 0) {
			$("#msg_1").html("错误");
			WebSpeech.speak("错误");
			$("#msg_1").css("color", "red");
		} else if (i == 1) {
			var msg="";
			if(curSku==""){
				curSku=sku;
				skuMap=new Map(); 
				skuMap.put(sku,1);
				msg="新商品";
			}else{
				if(curSku==sku){
					msg="正确";
				}else{
					if(skuMap.get(sku)==null){
						skuMap.put(sku,1);
						msg="新商品";
					}else{
						msg="已有新商品";
					}
					curSku=sku;
				}
			}
			$("#msg_1").css("color", "green");
			$("#msg_1").html(msg);
			WebSpeech.speak(msg);
		} else if (i == -1) {
			$("#msg_1").css("color", "red");
			$("#msg_1").html(sku + "超量");
			WebSpeech.speak("超量");
		} else if (i == 2) {
			$("#msg_1").css("color", "green");
			$("#msg_1").html("结束");
			WebSpeech.speak("结束");
		}

		var lock_num = $("#lock_num").parent().attr('aria-checked');
		if (!(lock_num == 'true')) {
			$("#txt_num").val('');
		}

		var lock_sku = $("#lock_sku").parent().attr('aria-checked');
		if (!(lock_sku == 'true')) {
			$("#txt_sku_1").val('');
			$("#txt_sku_1").focus();
		}
		else {
			$("#txt_num").focus();
		}
		
		clearBatch();
		batchTime = 0;
	}

	// 完成点收等操作
	function complete(obj){
		var lpnNum=$("#txt_lpn").val().trim();
		if(lpnNum.length==0){
			$("#msg_1").css("color", "red");
			$("#msg_1").html("LPN不能为空!");
			$("#txt_lpn").focus();
			return false;
		}
		$(obj).attr("disabled",true);
		var errorflag = $("#error_flag").val();
		var billId="${task.id}";
		var warehouseCode="${task.inwarehouseCode}";
		var jsonT = "[";
		var i=0;
		$("#boxItem").find("tr").each(function() {
			var tdArr = $(this).children();
			if(i==0){
	         jsonT +="{sku:\""+tdArr.eq(1).text()+ "\",batchCode:\""+tdArr.eq(2).text()+"\",productDate:\"" + 
	         		tdArr.eq(3).text()+"\",expireDate:\"" + tdArr.eq(4).text()
	        	 +"\",skuname:\""+tdArr.eq(5).text().replace(/"/g,"“")+"\",num:\""+tdArr.eq(7).text()+"\"}";
			}else{
		     jsonT +=",{sku:\""+tdArr.eq(1).text()+"\",batchCode:\""+tdArr.eq(2).text()+"\",productDate:\"" + 
	     		tdArr.eq(3).text()+"\",expireDate:\"" + tdArr.eq(4).text() + 
	     		"\",skuname:\""+tdArr.eq(5).text().replace(/"/g,"“")+"\",num:\""+tdArr.eq(7).text()+"\"}";
			}
			i++;
		});
	    jsonT += "]";
	    $.ajax({
			   type : 'post',
				url : '${ctx}/v2_instorageBillNew/confirmReceive',
				async:false,
				data : {
					skus:jsonT,
					lpnNum:lpnNum,
					billCode:"${task.billCode}",
					billId:billId,
					errorflag:errorflag,
					warehouseCode:warehouseCode
				},
				dataType : 'json',
				success : function(data) {
					var status=data.status;
					var content = data.content;
					var rowNum = 1 ;
					if( status=='success'){
						if(confirm("是否打印上架单?")){
							print(obj);
						}else{
							window.location.href = "${ctx}/v2_instorageBillNew/toInstorageCountPageNew/"+"${task.id}";
						}
					}else{
						$(obj).attr("disabled",false);
						alert(content);
					}
					curSku="";
					skuMap="";
				},
				error : function() {
					curSku="";
					skuMap="";
					$(obj).attr("disabled",false);
					alert("网络繁忙，请稍后重试...");
				}
			}); 
	}
	
	// 打印操作
	function print(item){
		$(item).attr("href","#printUpTask");
		$(item).attr("data-toggle","modal");
		packFormDefaultPrinter("upTaskStylePrint"); 	
	}
	
	// 打印上架单的操作
	function printUpTask(){
	  	$.ajax({
			"type" : "post",
			"url" : "${ctx}/v2_instorageBillNew/ajaxPrintLpnUpTask",
			"dataType" : "json",
			"data" : {
				lpn : $("#txt_lpn").val().trim(),
				billCode:"${task.billCode}"
			},
			success : function(data) {
				if(data.status == 1){
					/* var page=$("#upTaskStylePrintPage").val().trim();
					$.each(data.content, function(i,r) {
						printUpTaskOne(r,page);
					}); */
					printSJPage(data);
				}else{
					jAlert(data.content);
				}
				window.location.href = "${ctx}/v2_instorageBillNew/toInstorageCountPageNew/"+"${task.id}";
			},
			error : function() {
				jAlert("服务器异常");
			}
		});
	}

	function printSJPage(data){
		  var instorageBill=data.instorageBill;
		  var receiptDate=data.receiptDate==""? "":data.receiptDate[0].createTime;
			var str ="";
			str += "<table cellpadding='0' cellspacing='0' align = 'center' border='1'>";
			str += "<thead>";
			str += "<th  colspan= '4'>客户单号:"+instorageBill.aboutCode+"</th ><th  colspan= '3'>商家:"+instorageBill.customer.customerName+"</th >";
			str += "</tr>";
			str += "</thead>";
			str += "<tbody>";
			str += "<tr>";
			str += "<td colspan= '4' align = 'left'>入库单号:"+instorageBill.billCode+"</td><td colspan='3' ></td>";
			str += "</tr>";
			str += "<tr style='font-size:12pt'><td width='6%'>序号</td><td width='15%'>报损状态</td><td width='10%'>LPN</td><td width='18%'>sku</td><td width='31%'>sku名称</td><td width='10%' >待上架数量</td><td width='10%'>库位编码</td></tr>";
			$.each(data.instorageBillItemSJList,function(i){
				str +="<tr style='font-size:12pt' ><td>"+(i+1)+"</td><td>"+data.instorageBillItemSJList[i].errorFlag+"</td><td>"+data.instorageBillItemSJList[i].lpn+"</td><td>"+data.instorageBillItemSJList[i].sku+"</td><td>"+data.instorageBillItemSJList[i].skuName+"</td><td align = 'right'>"+data.instorageBillItemSJList[i].unUpNum+"</td>"+
					"<td></td></tr>";
			})
			str += "</tbody>";
			str += "<tfoot align = 'center'>";
			str += "<tr><td colspan= '5'></td><td align = 'right' tdata='Sum' format='#'>######</td><td></td></tr>";
			str += "<tr><td colspan= '2' align = 'left'>收货人:</td><td colspan= '2' align = 'left'>打印日期:"+date2str(new Date(),"yyyy-MM-d h:m:s")+"</td><td colspan= '3' align = 'left'>收货日期:"+receiptDate+"</td></tr>";
			str += "</tfoot>";
			str += "</table>";
			printTableAndBARCODE(instorageBill.billCode,$("#upTaskStylePrint").val(),"A4",$("#upTaskStylePrintPage").val(),0,154,45,10,str);
	}
	  
	function initLodop() {
		LODOP = getLodop(document.getElementById('LODOP_OB'), document.getElementById('LODOP_EM'));
	}
	
</script>
</head>

<body>
	<section class="content">

		<table id="contentTable" class="table  table-bordered table-condensed">
			<thead>
				<tr>
				<th style="text-align: center; color: white;"
					bgcolor="#3c8dbc">点收</th>
					</tr>
			</thead>
			<tr>
				<td>
					<span style="margin-left: 10px;">LPN(跟踪号):</span> 
				   <input id="txt_lpn" type="text"  onkeypress="lpnChange(event);"/> 
				</td>
			</tr>
			<tr>
				<td>
				<span style="margin-left: 10px;">是否报损件:</span> 
				<select
					id="error_flag" class="oldSelectStyle" onchange="errorChange();">
						<option value="noterror">完好件</option>
						<option value="error">破损件</option>
				</select> 
				<span style="margin-left: 10px;">SKU:</span> 
				<!-- <input id="txt_sku_1" type="text" onkeypress="sku1Change(event);" required onblur="keydown_1()" onkeydown="if(event.keyCode == '13'){keydown_key();}"/> -->
				<input id="txt_sku_1" type="text" oninput="sku1Change();" required onkeydown="if(event.keyCode == '13'){keydown_key();}"/>
				<input id="lock_sku" name="lock_sku" type="checkbox"  >锁定SKU</input>
				<div style="display:none;" class="txt_batchCode">
					<span style="margin-left: 10px;">批次号:</span>
					<input id="txt_batchCode" type="text"/>
				</div>
				<div style="display:none;" class="txt_expireDate">
					<span style="margin-left: 10px;">生产日期:</span>
					<input id="txt_productDate" type="text" />
				</div>
				<div style="display:none;" class="txt_expireDate">
					<span style="margin-left: 10px;">过期日期:</span>
					<input id="txt_expireDate" type="text" />
				</div>
					
				<span style="margin-left: 10px;">数量:</span> 
					<input id="txt_num" type="text" oninput="numChange()" onkeydown="if(event.keyCode == '13'){numAdd();}"/> 
					<input id="lock_num" name="lock_num" type="checkbox" checked="checked" >锁定数量</input>
					<span style="margin-left: 12px; margin-top: 10px; color: red; font-weight: bold;" id="msg_1"></span></td>
			</tr>
			<tr>
				<td>
					
					<a class="btn btn-primary" onclick="complete(this)">确认收货</a>
					<a class="btn btn-primary" href = "${ctx}/v2_instorageBillNew/v2_toInstorageBillListPage">返回</a>
				</td>
			</tr>
		</table>

		<!-- 数据 -->
		<table class="table" style="margin-top: 0px;">
			<thead>
				<tr><th style="text-align:center;color:white" colspan="11"
					bgcolor="#3c8dbc">入库数据</th></tr>
				<tr>
					<th style="width: 50px;">序号</th>
					<th style="width: 150px;">SKU</th>
					<th style="width: 150px;">批次号</th>
					<th style="width: 150px;">生产日期</th>
					<th style="width: 150px;">过期日期</th>
					<th style="width: 150px;">商品名称</th>
					<th style="width: 50px;">预约数量</th>
					<th style="width: 50px;">扫描数量</th>
					<th style="width: 50px;">已收货数量</th>
					<th style="width: 50px;">上架数量</th>
					<th style="width: 150px;">报损状态</th>
				</tr>
			</thead>
			<tbody id="boxItem">
				<c:forEach items="${items}" var="t" varStatus="i">
					<tr>
						<td >${i.count }</td>
						<td >${t.sku}</td>
						<td >${t.batchCode}</td>
						<td >${t.productDate}</td>
						<td >${t.expireDate}</td>
						<td >${t.skuName}</td>
						<td >${t.goodsNum}</td>
						<td >0</td>
						<c:choose>
							<c:when test="${t.countNum gt 0}">
								<td >${t.countNum}</td>
							</c:when>
							<c:otherwise>
								<td >0</td>
							</c:otherwise>
						</c:choose>
						<c:choose>
							<c:when test="${t.upNum gt 0}">
								<td >${t.upNum}</td>
							</c:when>
							<c:otherwise>
								<td >0</td>
							</c:otherwise>
						</c:choose>
						<td ><c:if test="${t.errorFlag eq 'noterror'}">
							完好件
						</c:if>
						<c:if test="${t.errorFlag eq 'error'}">
							破损件
						</c:if></td>
					</tr>
				</c:forEach>
			</tbody>

		</table>
		
		<!-- 打印按钮选择打印机 -->
	<div class="modal fade"  id="printUpTask">
	<div class="modal-dialog" >
	<div class="modal-content"  >
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal"
					aria-hidden="true">
					×
				</button>
				<h3 id="myModalLabel">
                    打印上架任务信息
				</h3>
				<span id="messageLable"></span>
				<input type="hidden" id="taskCode"/>
			</div>
			<div class="modal-body">
				<div class="control-group">
					<div class="controls">
						  选择打印机:
						<select id="upTaskStylePrint" name="upTaskStylePrint" >

						</select>
					</div>
					<div class="controls">
						  打印张数:
						<input type="text" id="upTaskStylePrintPage" name="upTaskStylePrintPage" value="1"/>
					</div>
				</div>
			</div>

			<div class="modal-footer">
				<a class="btn btn-primary" data-dismiss="modal" aria-hidden="true" onclick="printUpTask()"> 立即打印 </a>
				<a class="btn" data-dismiss="modal" aria-hidden="true"> 关闭 </a>
			</div>
		</div>
		</div>
		</div>
	</section>
</body>
</html>
